package com.syxbbs.forum.services.Impl;

import com.syxbbs.forum.Utils.StringUtils;
import com.syxbbs.forum.common.ResultCode;
import com.syxbbs.forum.dao.ArticleReplyMapper;
import com.syxbbs.forum.exception.ApplicationException;
import com.syxbbs.forum.model.ArticleReply;
import com.syxbbs.forum.services.IArticleReplyService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class IArticleReplyImpl implements IArticleReplyService {
    @Resource
    ArticleReplyMapper articleReplyMapper;

    @Resource
    ArticleServiceImpl articleService;

    @Transactional
    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply==null || articleReply.getArticleId()==null
                || articleReply.getPostUserId()==null
                || StringUtils.isEmpty(articleReply.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());

        }
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date=new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        articleReply.setLikeCount(0);
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(ResultCode.ERROR_SERVICES.toString());

        }
        //更新帖子表回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("帖子回复成功"+articleReply.getReplyId());


    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if (articleId==null || articleId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        List<ArticleReply> results = articleReplyMapper.selectByArticleId(articleId);
        return results;

    }


}
